#!/usr/bin/env python
# coding:utf-8
'''
DMZ城市登陆日统计
'''
import os,sys,common.db
from logging import *
from common.date_time import *


def IPToInt(ipaddr):
    sectionList = ipaddr.split(".")
    return ((int)(sectionList[0]) << 24) + ((int)(sectionList[1]) << 16) +((int)(sectionList[2]) << 8) +(int)(sectionList[3])

def GetCityByIP(cur,ipaddr):
    ip = IPToInt(ipaddr)
    strSql = 'select city from dmz_resource.ip_lib where ip1 < %d and ip2 > %d'%(ip,ip)
    cur.execute(strSql)
    rs = cur.fetchone()
    if rs is not None:
        return rs[0]
    return 0


def CityLoginDay(strCurDay):
    log(INFO,'StatDay : '+ strCurDay)
    strDay = strCurDay.replace('-','')

    # 连接数据库
    cnnBill = common.db.connect('billDB')
    cnnWeb = common.db.connect('DMZwebDB')
    curBill = cnnBill.cursor()
    curWeb = cnnWeb.cursor() 
    
    # 清除当天已有数据
    strSql = 'delete from statisticdb.DMZCityLoginDay where `Date`=%s'%(strDay)
    log(INFO, strSql)
    rowsDeleted = curBill.execute(strSql)
    cnnBill.commit()
    log(INFO,'Clear current day city login success!(DeletedCount=%d)', rowsDeleted)

    #查询每天登陆记录
    strSql = 'select zoneid, roleid, ipaddr from dmz_bill_%s.login group by zoneid, roleid order by zoneid'%(strDay)
    zoneList = {}
    curBill.execute(strSql)
    counter = 0
    rs = curBill.fetchone()
    while rs is not None:
        zoneid,roleid,ipaddr = rs
        city = GetCityByIP(curWeb,ipaddr)
        cityList = {}
        if zoneList.has_key(zoneid):
            cityList = zoneList[zoneid]
        if cityList.has_key(city):
            cityList[city] += 1
        else:
            cityList[city] = 1
        zoneList[zoneid] = cityList
        counter += 1
        if (counter % 1000) == 0:
            log(INFO,'Query city login count progress!(zoneid=%d, cityCount=%d, counter=%d)'%(zoneid,len(cityList),counter))
        rs = curBill.fetchone()
    log(INFO,'Query city login count compeleted!(counter=%d)'%(counter))

    #插入城市登陆统计数据
    counter = 0
    for zoneid in zoneList:
        cityList = zoneList[zoneid]
        for city in cityList:
            strSql = 'insert into statisticdb.DMZCityLoginDay(`Date`,`ZoneID`,`City`,`LoginCount`) values(%s, %d, %d, %d)'%(strDay,zoneid,city,cityList[city])
            rowsCount = curBill.execute(strSql)
            counter += 1
            #if (counter % 100) == 0:
            log(INFO,'Insert city login day progress!(counter=%d)'%(counter))
    cnnBill.commit()
    log(INFO,'Insert city login day success!')

    curBill.close()
    curWeb.close()
    cnnBill.close()
    cnnWeb.close()


if __name__ != "__main__":
    
    # 检验输入参数,如果参数为空,返回昨天日期
    if len(sys.argv) > 3:
        strBeginDay = sys.argv[2]
        strEndDay = sys.argv[3]
        if len(strBeginDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        if len(strEndDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        for strCurDay in intervalDay(strBeginDay,strEndDay):
            CityLoginDay(strCurDay)
    elif len(sys.argv) > 2:
        strCurDay = sys.argv[2]
        if len(strCurDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        CityLoginDay(strCurDay)
    else:
        strCurDay = GetDay(-1) ##"2010-01-14"
        CityLoginDay(strCurDay) 
    
